<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useSpiritualRoot } from '../../../../composables';
import { EVENTS, GameKernel } from '../../../../game';
import type { SpiritualRootKey } from '../../../../game/model/spiritual-root';
import { FIVE_ELEMENT } from '../../../../game/constants/five-elements';

const { state: spiritualRootState } = useSpiritualRoot();

const open = ref(false);
const title = ref('灵根蜕变');

const currentSpiritualRoot = ref<SpiritualRootKey>(FIVE_ELEMENT.METAL);

const currentSpiritualRootInfo = computed(() => {
  return spiritualRootState.value.spiritualRootInfo[currentSpiritualRoot.value];
});

function show(key: SpiritualRootKey) {
  const condition = spiritualRootState.value.spiritualRootInfo[key];
  if (condition.upgradeConditionProgress.length === 0) {
    GameKernel.inst.bus.emit(EVENTS.GAME_MESSAGE, '无法蜕变');
    return;
  }
  GameKernel.inst.bus.emit(EVENTS.SPIRITUAL_ROOT_STATE_UPDATE);
  currentSpiritualRoot.value = key;
  if (!currentSpiritualRoot.value) return;
  open.value = true;
}

function hide() {
  open.value = false;
}

function onUpgradeClick() {
  if (!currentSpiritualRoot.value) return;
  GameKernel.inst.bus.emit(
    EVENTS.SPIRITUAL_ROOT_UPGRADE,
    currentSpiritualRoot.value
  );
}

onMounted(() => {
  GameKernel.inst.bus.on(EVENTS.SPIRITUAL_ROOT_UPGRADE_COMPLETED, () => {
    if (currentSpiritualRootInfo.value.upgradeConditionProgress.length === 0) {
      hide();
    }
  });
});

defineExpose({
  show,
  hide,
});
</script>

<template>
  <a-modal
    v-model:open="open"
    wrap-class-name="spiritual-root-upgrade-modal"
    :centered="true"
    :closable="false"
    :footer="null"
  >
    <template #title>
      <div class="w-full text-center">{{ title }}</div>
    </template>
    <div v-if="currentSpiritualRootInfo">
      <div>
        <div>蜕变条件：</div>
        <div
          v-for="(
            condition, index
          ) in currentSpiritualRootInfo.upgradeConditionProgress"
          :key="index"
        >
          - {{ condition.description }}
        </div>
      </div>
      <div class="flex justify-center pt-2">
        <a-button
          :disabled="!currentSpiritualRootInfo.canUpgrade"
          @click="onUpgradeClick"
        >
          蜕变
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style>
.spiritual-root-upgrade-modal .ant-modal .ant-modal-content {
  padding: 8px;
}
</style>
